package com.jh.fcsm.service.inf.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jh.fcsm.beans.inf.InfSqlCode;
import com.jh.fcsm.beans.inf.InfSqlType;
import com.jh.fcsm.beans.inf.vo.InfSqlCodeVo;
import com.jh.fcsm.common.BaseServiceImpl;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.constant.CommonConstant;
import com.jh.fcsm.dao.inf.InfSqlCodeMapper;
import com.jh.fcsm.dao.inf.InfSqlTypeMapper;
import com.jh.fcsm.service.inf.InfSqlCodeService;
import com.jh.fcsm.util.security.UUIDUtils;
import com.jh.fcsm.util.txt.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @Description: API接口配置Service业务层处理
 * 
 * @author linqiang
 * @date 2022-08-01
 */
@Service
@Transactional(readOnly = true)
public class InfSqlCodeServiceImpl extends BaseServiceImpl<InfSqlCodeMapper, InfSqlCode> implements InfSqlCodeService {
	
	private static final Logger logger = LoggerFactory.getLogger(InfSqlCodeServiceImpl.class);
    @Autowired
    private InfSqlCodeMapper infSqlCodeMapper;
    
    @Autowired
    private InfSqlTypeMapper infSqlTypeMapper;

	@Override
	@Transactional(readOnly = false)
	/**
	 *@Description: 保存或更新API接口配置
	 *@param infSqlCode API接口配置对象
	 *@return String API接口配置ID
	 *@Author: linqiang
	 */
	public String saveOrUpdateInfSqlCode(InfSqlCode infSqlCode) {
		if(infSqlCode==null){
			throw new ServiceException("数据异常");
		}
		if(!checkCode(infSqlCode.getCode(), infSqlCode.getId())) {
			throw new ServiceException("接口编码已经存在");
		}

		infSqlCode.setSqlCode(new String(
				Base64.getDecoder().decode(infSqlCode.getSqlCode()), StandardCharsets.UTF_8)
		);
		
		if(StringUtils.isEmpty(infSqlCode.getId())){
			//新增
			infSqlCode.setId(UUIDUtils.getUUID());
			infSqlCodeMapper.insertSelective(infSqlCode);
		}else{
			//避免页面传入修改
			infSqlCode.setYn(null);
			infSqlCodeMapper.updateByPrimaryKeySelective(infSqlCode);
		}
		return infSqlCode.getId();
	}
	
	 /**
     * @Description 校验CODE重复
     * @param code
     * @param id
     * @return boolean 
     * @author linqiang
     */
    private boolean checkCode(String code, String id) {
        Example example = new Example(InfSqlCode.class);
        example.createCriteria().andEqualTo("code", code).andEqualTo("yn", CommonConstant.FLAG_YES);
        List<InfSqlCode> list = infSqlCodeMapper.selectByExample(example);
        if (list.isEmpty()) {
            return true;
        }
        // 编辑
        // 判断某字符串是否不为空且长度不为0且不由空白符(whitespace)构成，等于!isBlank(String str)
        if (!StringUtils.isEmpty(id)) {
            for (InfSqlCode bean : list) {
                if (!bean.getId().equals(id)) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

	@Override
	@Transactional(readOnly = false)
	/**
	 *@Description: 删除API接口配置
	 *@param id void API接口配置ID
	 *@Author: linqiang
	 */
	public void deleteInfSqlCode(List<String> ids) {
		for(String id:ids){
			//TODO 做判断后方能执行删除
			InfSqlCode infSqlCode=infSqlCodeMapper.selectByPrimaryKey(id);
			if(infSqlCode==null){
				throw new ServiceException("非法请求");
			}
			//逻辑删除
			InfSqlCode teminfSqlCode=new InfSqlCode();
			teminfSqlCode.setYn(CommonConstant.FLAG_NO);
			teminfSqlCode.setId(infSqlCode.getId());
			infSqlCodeMapper.updateByPrimaryKeySelective(teminfSqlCode);
		}
	}

	/**
	 *@Description: 查询API接口配置详情
	 *@param id
	 *@return InfSqlCode
	 *@Author: linqiang
	 */
    @Override
	public InfSqlCode findById(String id) {
		return infSqlCodeMapper.selectByPrimaryKey(id);
	}


	/**
	 *@Description: 分页查询API接口配置
	 *@param infSqlCodeVo
	 *@return PageInfo<InfSqlCode>
	 *@Author: linqiang
	 */
	@Override
	public PageInfo<InfSqlCode> findPageByQuery(InfSqlCodeVo infSqlCodeVo) {
		PageHelper.startPage(infSqlCodeVo.getPageNum(),infSqlCodeVo.getPageSize());
		Example example=new Example(InfSqlCode.class);
		Criteria criteria=example.createCriteria();
		criteria.andEqualTo("yn",CommonConstant.FLAG_YES);
		//查询条件
		if(!StringUtils.isEmpty(infSqlCodeVo.getTypeCode())&& !"0".equals(infSqlCodeVo.getTypeCode())){
			List<String> typeCodeList=new ArrayList<String>();
			findTypeList(infSqlCodeVo.getTypeCode(),typeCodeList);
			criteria.andIn("typeCode", typeCodeList);
		}
		if(!StringUtils.isEmpty(infSqlCodeVo.getCode())) {
			criteria.andLike("code", "%"+infSqlCodeVo.getCode()+"");
		}
		
		example.orderBy("updateTime").desc();
		List<InfSqlCode> infSqlCodeList=infSqlCodeMapper.selectByExample(example);
		return new PageInfo<InfSqlCode>(infSqlCodeList);
	}
	
	
	public void findTypeList(String typeCode,List<String> typeCodeList){
		typeCodeList.add(typeCode);
		Example exampleType=new Example(InfSqlType.class);
		Criteria criteriaType=exampleType.createCriteria();
		
		criteriaType.andEqualTo("yn",CommonConstant.FLAG_YES).andEqualTo("parentCode", typeCode);
		List<InfSqlType> typeList= infSqlTypeMapper.selectByExample(exampleType);
		if(!CollectionUtils.isEmpty(typeList)) {
			for(InfSqlType type:typeList) {
				findTypeList(type.getTypeCode(), typeCodeList);
			}
		}
	}
	
	
}
